﻿﻿/**
 * ドロップダウン処理クラス
 * @param targetList 対象TEXTオブジェクト配列
 * @param panel ドロップダウン用DIVオブジェクト
 * @param canvasName 描画位置ID
 * @return
 */
var CItemDropDownList = function(targetList,panel,canvasName){
	this.xmlHttp = this.getXMLHttpRequest();
	this.serverURL = 'http://127.0.0.1:8080/tytpro/common/js/dropdown/item.xml';
	this.panel = panel;
	this.canvasName = canvasName;//this.panel.id+"_canvas";
	this.tableName = this.panel.id+"_table";
	
	
	this.focusObject = null;
	this.focus = false;
	this.closeTimerId = null;
	
	this.keyUpEvent = null;
	this.clickEvent = null;
	this.itemList=[];
	this.targets = [];
	
	var me = this;
	
	for ( var i=0; i<targetList.length; i++ ){
		me.targets[i] = targetList[i];
		if ( me.targets[i].addEventListener ){
			me.targets[i].addEventListener('keyup', function(evt) { me.OnKeyUpObserver(me,evt) }, false);
			me.targets[i].addEventListener('focus', function(evt) { me.OnFocusObserver(me,evt) }, false);
			me.targets[i].addEventListener('blur', function(evt) { me.OnBlurObserver(me,evt) }, false);
		}else if( me.targets[i].attachEvent ){
			me.targets[i].attachEvent('onkeyup', function(evt) { me.OnKeyUpObserver(me,window.event); });
			me.targets[i].attachEvent('focus', function(evt) { me.OnFocusObserver(me,window.event); });
			me.targets[i].attachEvent('onblur', function(evt) { me.OnBlurObserver(me,window.event); });
		}
		
	}
	
	var allList = panel.getElementsByTagName("*");
	for ( var i=0; i<allList.length; i++ ){
		var obj = allList[i];
		obj.IsPanelObjectGroup = true;
		
		if ( obj.addEventListener ){
			obj.addEventListener('focus', function(evt) { me.OnFocusObserver(me,evt) }, false);
			obj.addEventListener('blur', function(evt) { me.OnBlurObserver(me,evt) }, false);
		}else if( obj.attachEvent ){
			obj.attachEvent('onfocus', function(evt) { me.OnFocusObserver(me,window.event); });
			obj.attachEvent('onblur', function(evt) { me.OnBlurObserver(me,window.event); });
		}
	}
	
}

CItemDropDownList.prototype.setKeyUpEvent = function(func){
	this.keyUpEvent=func;
};
CItemDropDownList.prototype.setSelectEvent = function(func){
	this.clickEvent=func;
};


/**
 * 設定したテキストボックスのキーアップイベント
 * @param object 管理インスタンス
 * @param evt 発生イベント
 * @return
 */
CItemDropDownList.prototype.OnKeyUpObserver = function(object,evt){
	var sender = null;
	if ( evt.target ){
		sender = evt.target;
	}else{
		sender = evt.srcElement;
	}
	
	var table = document.getElementById(this.tableName);
	if ( evt.keyCode == 40 ){
		if ( table ){
			var manager = table.ManageClass;
			manager.doMoveNext();
		}		
	}else if ( evt.keyCode == 38 ){
		if ( table ){
			var manager = table.ManageClass;
			manager.doMovePrev();
		}
	}else if ( evt.keyCode == 13 ){
		if ( table ){
			var manager = table.ManageClass;
			manager.scroll();
			var row = manager.getSelectedObject();
			try{
				if ( row != null){
					var idx = row.sectionRowIndex
					var item = object.itemList[idx];
					this.clickEvent(object,sender,item);
				}
			}catch(ex){
			}
		}
	}else{
		object.keyUpEvent(object,sender,evt);
	}
};

/**
 * 管理グループのフォーカス処理
 * @param object 管理インスタンス
 * @param evt 発生イベント
 * @return
 */
CItemDropDownList.prototype.OnFocusObserver = function(object,evt){
	var sender = null;
	if ( evt.target ){
		sender = evt.target;
	}else{
		sender = evt.srcElement;
	}
	if ( !sender.IsPanelObjectGroup && this.focusObject != sender ){
		this.OnCloseTimeOut(object,evt);
	}
	
	this.focus = true;
	if ( this.closeTimerId != null ){
		window.clearTimeout(this.closeTimerId);
		this.closeTimerId = null;
	}
};

/**
 * 管理グループのフォーカスが外れた場合の処理
 * @param object 管理インスタンス
 * @param evt 発生イベント
 * @return
 */
CItemDropDownList.prototype.OnBlurObserver = function(object,evt){
//閉じない様にコメントアウト
//	this.focus = false;
//	var me=this;
//	if ( this.closeTimerId == null ){
//		this.closeTimerId = window.setTimeout(function(){me.OnCloseTimeOut(me,evt);},200);
//	}
};

/**
 * ドロップダウンウインドウのクローズ処理
 * @param object 管理インスタンス
 * @param evt 発生イベント
 * @return
 */
CItemDropDownList.prototype.OnCloseTimeOut = function(object,evt){
	if ( this.closeTimerId != null ){
		window.clearTimeout(this.closeTimerId);
		this.closeTimerId = null;
	}
	if ( !this.focus ){
		object.panel.style.display="none";
	}
};

/**
 * XML受信要求
 * @param object 管理インスタンス
 * @param sender 発生オブジェクト[textbox]
 * @param param 要求パラメーター
 * @return
 */
CItemDropDownList.prototype.doXmlRequest = function(object,sender,param){
	var me = this;
	var clientDate = new Date();
	var url = this.serverURL + '?' + param +'&ctm=' + clientDate.getTime();
	
	me.xmlHttp.open("POST",url);
	me.xmlHttp.onreadystatechange = function() {
		me.onReadyStateChange(me,sender,me.xmlHttp);
	}
	me.xmlHttp.send(null);
};

/**
 * XML受信状況に変動があった場合の処理(非同期処理)
 * @param object 管理インスタンス
 * @param sender 発生オブジェクト[textbox]
 * @param evt 発生イベント
 * @return
 */
CItemDropDownList.prototype.onReadyStateChange = function(object,sender,xmlHttp){
	if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
		
		var xml = xmlHttp.responseXML;
		var rootNodes = xml.getElementsByTagName("list");
		var rootNode = rootNodes[0];
		var json = JSONConvert(rootNode);
		
		if (json==null) {
			this.itemList = null;
		} else {
			this.itemList = json.item;
			if (this.itemList.length == null) {
				//配列化
				this.itemList=[this.itemList];
			}
		}
		if (this.createTable(object,sender,json)) {
			
		}
		
		var canvas = document.getElementById(this.canvasName);
		//canvas.innerHTML=tableText;
		
		var eventSender = sender;
		var me=this;
		var table = document.getElementById(this.tableName);
		if ( table.addEventListener ){
			table.addEventListener('click', function(evt) { object.ListOnClickObserver(me,eventSender,evt) }, false);
			table.addEventListener('focus', function(evt) { object.OnFocusObserver(me,evt) }, false);
			table.addEventListener('blur', function(evt) { object.OnBlurObserver(me,evt) }, false);
		}else if( table.attachEvent ){
			table.attachEvent('onclick', function(evt) { object.ListOnClickObserver(me,eventSender,window.event); });
			table.attachEvent('onfocus', function(evt) { object.OnFocusObserver(me,window.event); });
			table.attachEvent('onblur', function(evt) { object.OnBlurObserver(me,window.event); });
		}
		var tableClass = new CListTable(table);
		tableClass.setCanvas(canvas);
		
	}
};

CItemDropDownList.prototype.createTable=function(object,sender,json) {
	var itemList = this.itemList;
	var tableText = "<table cellspacing='0' cellpadding='0' border='0' id='"+this.tableName+"'>";
	if (itemList!=null && itemList.length!=0) {
		for ( var i=0; itemList && i<itemList.length; i++ ){
			var item = itemList[i];
			
			tableText+= "<tr>";
			tableText+= "<td>"+item.itemcd+"</td>";
			tableText+= "</tr>";
		}
	} else {
		tableText+= "<tr>";
		tableText+= "<td>該当なし</td>";
		tableText+= "</tr>";
		tableText+= "</table>";
	}
	tableText+= "</table>";
	
	var canvas = document.getElementById(this.canvasName);
	canvas.innerHTML=tableText;
}


/**
 * ドロップダウンリストのクリック処理
 * @param object 管理インスタンス
 * @param sender 発生オブジェクト[tr]
 * @param evt 発生イベント
 * @return
 */
CItemDropDownList.prototype.ListOnClickObserver = function(object,sender,evt){
	var srcElement = null;
	if ( evt.target ){
		srcElement = evt.target;
	}else{
		srcElement = evt.srcElement;
	}
	try{
		var idx = srcElement.parentNode.sectionRowIndex
		var item = object.itemList[idx];
		this.clickEvent(object,sender,item);
	}catch(ex){
	}
};


/**
 * XMLリクエストオブジェクト取得処理
 * @return XMLHttpRequestオブジェクト
 */
CItemDropDownList.prototype.getXMLHttpRequest = function(){
	var xmlHttp = null;
	if(window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
};



/**
 * テーブル管理クラス
 **/
var CListTable = function(target){
	target.ManageClass = this;
	this.target=target;
	this.rows = [];
	this.selectedNo = -1;
	this.selectedObject = null;
	this.canvas = null;
	this.focusObject = null;
	
	
	var list = target.getElementsByTagName("tr");
	for ( var i=0; list && i<list.length; i++ ){
		var tr = list[i];
		tr.object = this;
		this.rows[i] = tr;
	}
	
	var me = this;
	if ( target.addEventListener ){
		target.addEventListener('mouseover', function(evt) { me.OnMouseOver(me,evt) }, false);
	}else if( target.attachEvent ){
		target.attachEvent('onmouseover', function(evt) { me.OnMouseOver(me,window.event); });
	}
}

CListTable.prototype.setCanvas = function(canvas){
	this.canvas = canvas;
};

CListTable.prototype.doMoveNext = function(){
	if ( this.selectedObject != null ){
		this.selectedObject.style.backgroundColor="";
		this.selectedObject.style.color="";
	}
	var object = this.getRowObject(this.selectedNo+1);
	if ( object != null ){
		this.selectedObject = object;
		this.selectedObject.style.backgroundColor="#037";
		this.selectedObject.style.color="#fff";
		this.selectedNo += 1;
	}else{
		this.selectedNo = this.rows.length;
	}
	this.scroll();
};

CListTable.prototype.doMovePrev = function(){
	if ( this.selectedObject != null ){
		this.selectedObject.style.backgroundColor="";
		this.selectedObject.style.color="";
	}
	var object = this.getRowObject(this.selectedNo-1);
	if ( object != null ){
		this.selectedObject = object;
		this.selectedObject.style.backgroundColor="#037";
		this.selectedObject.style.color="#fff";
		this.selectedNo -= 1;
	}else{
		this.selectedNo = -1;
	}
	this.scroll();
};

CListTable.prototype.doSelectObject = function(index){
	if ( this.selectedObject != null ){
		this.selectedObject.style.backgroundColor="";
		this.selectedObject.style.color="";
	}
	var object = this.getRowObject(index);
	if ( object != null ){
		this.selectedObject = object;
		this.selectedObject.style.backgroundColor="#037";
		this.selectedObject.style.color="#fff";
		this.selectedNo = index;
	}
};


CListTable.prototype.getSelectedObject = function(){
	var object = this.getRowObject(this.selectedNo);
	return object;
};

CListTable.prototype.getRowObject = function(no){
	if ( no>=0 && no<this.rows.length ){
		return this.rows[no];
	}
};

/**
 * リスト表示ウインドウスクロール処理
 */
CListTable.prototype.scroll = function(){
	if ( this.canvas == null ) return false;
	var rowNo = this.selectedNo;
	if ( rowNo < 0 || rowNo >= this.rows.length ) return false;
	try{
		var height = this.canvas.offsetHeight;
		var scrollTop = this.canvas.scrollTop;
		var currentTop = this.rows[rowNo].offsetTop;
		
		if ( currentTop>=scrollTop && currentTop<=(scrollTop+height) ){
			return false;
		}else{
			var top = currentTop-(height/2);
			this.canvas.scrollTop = top;
			return true;
		}
	}catch(ex){
	}
};


/**
 * ドロップダウンリストのマウスオーバー処理
 * @param object 管理インスタンス
 * @param evt 発生イベント
 * @return
 */
CListTable.prototype.OnMouseOver = function(object,evt){
	var sender = null;
	if ( evt.target ){
		sender = evt.target;
	}else{
		sender = evt.srcElement;
	}
	try{
		var tr = sender.parentNode;
		if ( tr.tagName && tr.tagName.toUpperCase() == "TR" ){
			var idx = tr.sectionRowIndex;
			this.doSelectObject(idx);
		}
	}catch(ex){
		alert(ex);
	}
};





















function calculateOffsetTop(field) {
  return calculateOffset(field, "offsetTop");
}

function calculateOffsetLeft(field) {
  return calculateOffset(field, "offsetLeft");
}

function calculateOffset(field, attr) {
  var offset = 0;
  while(field) {
    offset += field[attr]; 
    field = field.offsetParent;
  }
  return offset;
}


function JSONConvert(node){
	var type = node.nodeType;
	if ( isTextNode(node) ){
		var text = getTextValue(node);
		return text;
	}
	if ( type==1 ){
		var json = {};
		var nodeName = node.nodeName;
		var childs = node.childNodes;
		
		for (var i = 0; i<childs.length; i++){
			var child = childs[i];
			var obj = json[child.nodeName];
			
			if ( child.nodeType == 1 ){
				if ( obj ){
					var array = null;
					if ( !isArray(obj) ){
						array=[];
						array[array.length]=obj;
					}else{
						array=json[child.nodeName];
					}
					array[array.length]=JSONConvert(child);
					json[child.nodeName]=array;
				}else{
					json[child.nodeName]=JSONConvert(child);
				}
			}
		}
		return json;
	}
}

function isTextNode(node){
	if ( node.hasChildNodes() ){
		var childs = node.childNodes;
		for (var i = 0; i<childs.length; i++){
			var child = childs[i];
			if ( child.nodeType != 3 ) return false;
		}
	}
	return true;
}

function getTextValue(node){
	if ( node.hasChildNodes() ){
		var childs = node.childNodes;
		var child = childs[0];
		if ( child.nodeType == 3 ){
			return child.nodeValue;
		}
	}
	return null;
}

function isArray(array) {
　　return (typeof(array) == "object" && array != null &&
　　　　array.constructor.toString().indexOf(" Array(") >= 0);
}